package com.jxt.myjxtmanager.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.jxt.myjxtmanager.MyApplication;
import com.jxt.myjxtmanager.utils.Config;


public class DBHelper {

	private DaoMaster daoMaster;
	private DaoSession daoSession;
	private SQLiteDatabase db;
	private static DBHelper instance;
	Context appContext;

	//单例获取DBHelper(饿汉式)
	public synchronized static DBHelper getInstance() {
		if (instance == null) {
			instance = new DBHelper();
		}
		return instance;
	}
	
	private DBHelper(){
		appContext= MyApplication.getInstance().getApplicationContext();
	}

	
	public DaoMaster getDaoMaster(){
		if(daoMaster==null){
			DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(appContext, Config.DB.GREEN_DB_NAME, null);
			helper.setOnUpgrade(new DaoMaster.DevOpenHelper.OnDbUpgrade() {
				
				@Override
				public void onDbUpgrade(SQLiteDatabase db, int migrateVersion) {
					// TODO Auto-generated method stub
					if(migrateVersion==2){
						DaoMaster.createAllTables(db, true);
					}
				}
			});
			db=helper.getWritableDatabase();
			daoMaster=new DaoMaster(db);
		}
		return daoMaster;
	}
	
	
	public DaoSession getDaoSession(){
		if(daoMaster==null){
			if(daoMaster==null){
				daoMaster=getDaoMaster();
			}
			daoSession=daoMaster.newSession();
		}
		return daoSession;
	}
}
